package com.health.controller;

import com.aliyuncs.exceptions.ClientException;
import com.health.utils.Constant;
import com.health.utils.SMSUtil;
import com.health.vo.Result;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.Duration;

/**
 * 发送短信验证码-controller
 */
@RestController
@RequestMapping("/authCode")
public class AuthCodeController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 校验短信验证码-预约体检
     */
    @GetMapping("checkOrderCode/{phone}/{code}")
    public Result checkOrderCode(@PathVariable String phone,@PathVariable String code){
        //判断redis中的验证码是否匹配
        String key=Constant.ORDER_CODE+":"+phone;
        Object o = redisTemplate.opsForValue().get(key);
        if (o !=null && o.toString().equals(code)){
            //匹配成功
            return new Result(true,"验证码准确");
        }
        return new Result(false,"验证码错误");
    }

    /**
     * 发送短信验证码-预约体检
     */
    @GetMapping("/sendOrderCode/{phone}")
    public Result sendOrderCode(@PathVariable String phone) throws ClientException {
        //先从Redis中获取，判断是否已发送
        String key = Constant.ORDER_CODE + ":" + phone;

        //判断redis中的验证码是否过期,防止重复发送验证码
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey != null && hasKey) {
            //已发送过
            return new Result(false, "验证码已发送，请注意查收");
        }

        //生成6位随机数
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        //发送验证码
        boolean send = SMSUtil.send(phone, code);
        if (send) {
            //存储到Redis中，保留5分钟
            redisTemplate.opsForValue().set(key, code, Duration.ofMinutes(5));
            return new Result(true, "验证码发送成功");
        }

        return new Result(false, "验证码发送失败");
    }
}